<?php

global $_CONF;

$_CONF['debug'] = false;

App::loadAjax(array('Account', 'Smiles'), array
(
	'getUsersOnline',
	'changeImStatus',
	'searchFriends',
	'getMessages',
	'addMessage',
	'getImStatus',
	'loadEmoticons'
));

if ( !isset($_POST['xajax']) )
{
	App::membersOnly();
	
	$oTpl =& App::getTemplate();
	$oDb =& Database::get();
	$oReq =& App::getRequest();

	$iUserId = $oReq->get('userid');
	$sType = $oReq->get('type');

	$iTimeout = time() - App::getSetting('max_time_online') * 60;
	
	$aRow = $oDb->getRow("
		SELECT 
			u.id, u.user, o.userid, s.userid AS is_online
		FROM ". App::getT('user') ." AS u
			LEFT JOIN " . App::getT('msg_online') . " AS o ON(o.userid = u.id AND o.time > '". $iTimeout ."')
			LEFT JOIN " . App::getT('msg_online') . " AS s ON(s.userid = '" . App::getUser('id') . " ' AND s.time > '". $iTimeout ."')
		WHERE u.id = '". $oDb->escape($iUserId) ."'
	");
	$aRow['profile_info'] = App::format('Mod_Chat.view_users_profile', array($aRow['user']));

	if ( !isset($aRow['id']) )
	{
		exit('Error Code: Invalid User!');
	}
	
	if	(empty($aRow['is_online']))
	{
		$oTpl->assign(array(
			'sExtraHeader' => '<script type="text/javascript">
			window.resizeTo(700, 430);
			</script>',
			'bUserIsOffline' => true,
			'aUser' => $aRow,
			'iUserId' => $iUserId,
		));
		$oTpl->setTemplateFile('chat.html');		
	}
	else if (empty($aRow['userid'])) 
	{
		$oTpl->assign(array(
			'sExtraHeader' => '<script type="text/javascript">
			window.resizeTo(700, 430);
			</script>',
			'bIsOffline' => true,
			'aUser' => $aRow,
			'iUserId' => $iUserId,
		));
		$oTpl->setTemplateFile('chat.html');
	}
	else
	{	
		if ( $sType == 'request' )
		{
			// Check if we already requested a chat
			$aRequest = $oDb->getRow("SELECT requestid AS id FROM ". App::getT('msg_request') ." WHERE userid = '". App::getUser('id') ."' AND ruserid = '". $aRow['id'] ."'");
			
			// Check if the other user is requesting a chat
			$aRequested = $oDb->getRow("SELECT requestid AS id FROM ". App::getT('msg_request') ." WHERE ruserid = '". App::getUser('id') ."' AND userid = '". $aRow['id'] ."'");
			
			$aRequestRoom = $oDb->getRow("
				SELECT 
					r.requestid AS id 
				FROM ". App::getT('msg_room') ." AS r
					LEFT JOIN " . App::getT('msg_room') . " AS c ON(c.userid = '". $aRow['id'] ."')
				WHERE r.userid = '". App::getUser('id') ."' AND r.requestid = c.requestid
				ORDER BY r.time DESC LIMIT 0,1		
			");
		
			if ( isset($aRequest['id']) )
			{
				App::gotoUrl('public.account.messenger.chat', array('roomid' => $aRequest['id'], 'userid' => $aRow['id'], 'close' => 'yes'));
			}
			else if ( isset($aRequested['id']) )
			{	
				$oDb->_delete(App::getT('msg_request'), "requestid = '". $aRequested['id'] ."'");			
				App::gotoUrl('public.account.messenger.chat', array('roomid' => $aRequested['id'], 'userid' => $aRow['id']));
			}
			else if ( isset($aRequestRoom['id']) )
			{	
				App::gotoUrl('public.account.messenger.chat', array('roomid' => $aRequestRoom['id'], 'userid' => $aRow['id'], 'close' => 'yes'));
			}		
			else
			{
				$oDb->_delete(App::getT('msg_request'), "userid = '". App::getUser('id') ."' AND ruserid = '". $aRow['id'] ."'");
				$iRequestId = $oDb->insert(App::getT('msg_request'), array('userid' => App::getUser('id'), 'ruserid' => $aRow['id'], 'time' => time()));
				$oDb->insert(App::getT('msg_room'), array('requestid' => $iRequestId, 'userid' => App::getUser('id'), 'time' => time()));
				$oDb->insert(App::getT('msg_room'), array('requestid' => $iRequestId, 'userid' => $aRow['id'], 'time' => time()));
			}
			App::gotoUrl('public.account.messenger.chat', array('roomid' => $iRequestId, 'userid' => $aRow['id']));
		}

		if ( $sType == 'accept' && ($iRequestId = $oReq->get('requestid')) )
		{
			// $oDb->_delete(App::getT('msg_request'), "requestid = '". $iRequestId ."'");
			// $oDb->insert(App::getT('msg_chat'), array('requestid' => $iRequestId, 'text' => ''. App::getUser('user') .' joined the conversation', 'time' => time()));
			App::gotoUrl('public.account.messenger.chat', array('roomid' => $iRequestId, 'userid' => $aRow['id']));
		}

		$iRoomId = $oReq->getInt('roomid');
	
		if (!$iRoomId) 
		{
			exit('Error Code: No room ID!');
		}
		
		$iRoomCheck = $oDb->getField("SELECT COUNT(*) FROM ". App::getT('msg_room') ." WHERE requestid = '". $iRoomId ."' AND userid = '" . App::getUser('id') . "'");	
	
		if (!$iRoomCheck) 
		{
			exit('Error Code: Invalid Room!');	
		}
		
		$sJavaScript = '<script type="text/javascript">
		function confirmExit()
		{
			opener.window.document.getElementById(\'ajax_temp_content\').innerHTML=\'<iframe frameborder="0" width="0" height="0" src="' . App::getParam('url') . 'design/static/ajax.php?intelajax[module]=Account&intelajax[function]=deleteFromRoom&intelajax[params][roomid]=' . $iRoomId . '"><\/iframe>\';
		}
		window.onunload = confirmExit;
		function playsound(fn) 
		{
			var d = document.getElementById(fn);
			d.innerHTML = \'<embed src="'. App::getParam('url') .'file/player/beep.wav" autostart="true" hidden="true" volumn="100" look="false" />\';
		}
		'. ($oReq->get('close') ? 'window.close();' : '') .'
		</script>';	
		$sJavaScript .= "<script type=\"text/javascript\">\n\t\twindow.onload=clicktoHideAll;\n\t\tvar sDisplayIds = new Array('mainEmoticons');\n</script>";

		$oTpl->assign(array
		(
			'aUser' => $aRow,
			'iUserId' => $iUserId,
			'iRoomId' => $iRoomId,
		    'sExtraHeader' => ''. $sJavaScript .'<script type="text/javascript" src="design/js/tinymce/tiny_mce.js"></script>
		<script type="text/javascript">
		tinyMCE.init({
			mode : "exact",
			elements : "maintext",
			theme : "advanced",
			plugins : "enter",
			theme_advanced_buttons1 : "bold,italic,underline,separator,cut,copy,paste,separator,link,unlink,fontselect,fontsizeselect,separator,forecolor",
			theme_advanced_buttons2 : "",
			theme_advanced_buttons3 : "",
	        theme_advanced_toolbar_location : "top",
	        theme_advanced_toolbar_align : "center",
	        theme_advanced_statusbar_location : "bottom",
	        cleanup : false,
	        convert_newlines_to_brs : false,
	        force_br_newlines : true,
	        theme_advanced_resizing : true,
	        theme_advanced_resize_horizontal : true,
	        theme_advanced_more_colors : false,
			convert_urls : false,
			relative_urls : true		
		});</script>'
		));
		$oTpl->setTemplateFile('chat.html');
	}
}
?>